大家好,我是Leo
今天來介紹的是swaager如何套用在django上面
OK~~~ Let's go now!!!
Swagger 是一組用於編寫基於 REST 的 API 的開源open source 工具。它通過缺口、指定標準和提供編寫美觀、安全、高性能和可擴展的 API 所需的工具來簡化編寫 API 的過程。
想要把原本四散各處而且不完整的 API 文件整理,並且用一個對於工程師而言比較容易取得的方式管理。以下是圖示:
pip install drf_yasg
INSTALLED_APPS = [
'drf_yasg'
]
# py路徑
SWAGGER_SETTINGS = {
'DEFAULT_AUTO_SCHEMA_CLASS':'config.swagger.CustomSwaggerAutoSchema'
}
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions
schema_view = get_schema_view(
openapi.Info(
title='title',
default_version='v1',
description='description'
),
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
path('swagger/',schema_view.with_ui('swagger'),name='swagger')
]
這就是剛剛在settings設定DEFAULT_AUTO_SCHEMA_CLASS的路徑
from drf_yasg.inspectors import SwaggerAutoSchema
class CustomSwaggerAutoSchema(SwaggerAutoSchema):
def get_tags(self,operation_keys=None):
tags = super().get_tags(operation_keys)
if 'v1' in tags and operation_keys:
tags[0] = operation_keys[1]
return tags
class downloadYoutube(views.APIView):
permission_classes = (permissions.AllowAny,)
authentication_classes = []
@swagger_auto_schema(
operation_description='取得youtube下載資料',
tags=['Youtube'],
responses={200: 'OK'},
)
def get(self, request, *args, **kwargs):
data = request.data
serializer = self.serializer_class(data=data)
serializer.is_valid(raise_exception=True)
try:
self._delete_image(request)
except Exception as e:
msg = e.args if e else ''
logger.exception(str(e))
return Response(status=status.HTTP_400_BAD_REQUEST, data=msg)
return Response(status=status.HTTP_200_OK)
def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_body=None, query_serializer=None,manual_parameters=None, operation_id=None, operation_description=None, operation_summary=None,security=None, deprecated=None, responses=None, field_inspectors=None, filter_inspectors=None,paginator_inspectors=None, tags=None, **extra_overrides):
如下圖所示
Fetch error Internal Server Error http://127.0.0.1:8000/swagger/?format=openapi
無法加載 API 定義。 獲取錯誤內部服務器錯誤http://127.0.0.1:8000/api/v1/swagger/?format=openapi
我們必須找尋runserver下的錯誤代碼,再從錯誤代碼進行著手解決
今天先講解openai swaager文件
明天講解api製作匯出excel檔
我們明天見,各位掰掰~~~